// src/pages/Fenlei.jsx
import React, { useState, useEffect } from 'react';
import { Input, Button, List, Tabs, Card, Tag, Space, Toast, SpinLoading } from 'antd-mobile';
import axios from 'axios';
import { API_CONFIG } from '../config/api';
import './Fenlei.css';

function Fenlei() {
    const [activeTab, setActiveTab] = useState('all');
    const [searchValue, setSearchValue] = useState('');
    const [orders, setOrders] = useState([]);
    const [loading, setLoading] = useState(false);
    const [totalOrders, setTotalOrders] = useState(0);

    // 从后端获取订单数据
    const fetchOrders = async () => {
        try {
            setLoading(true);
            const response = await axios.get(API_CONFIG.ORDER.LIST, {
                params: {
                    page: 1,
                    pageSize: 50, // 获取更多订单用于筛选
                    status: '待取件' // 只获取待取件的订单
                }
            });
            
            if (response.data.code === 0) {
                setOrders(response.data.data.list);
                setTotalOrders(response.data.data.total);
            } else {
                Toast.show({
                    content: '获取订单失败',
                    position: 'center',
                });
            }
        } catch (error) {
            console.error('获取订单错误:', error);
            Toast.show({
                content: '网络错误，请稍后重试',
                position: 'center',
            });
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchOrders();
    }, []);

    const handleGrabOrder = async (orderId) => {
        try {
            // 这里需要从本地存储获取当前登录骑手的ID
            const rider = JSON.parse(localStorage.getItem('riderInfo'))|| '';
            console.log("🚀 ~ handleGrabOrder ~ rider:", rider)
            
            const response = await axios.post(API_CONFIG.RIDER.GRAB_ORDER, {
                riderId:rider._id,
                orderId: orderId
            });
            
            if (orderId != '') {
                rider.order= orderId;
                localStorage.setItem('riderInfo', JSON.stringify(rider));
                localStorage.setItem('currentOrderId', JSON.stringify(orderId));
                Toast.show({
                    content: '已记录订单！',
                    position: 'center',
                });
            } 
            if (response.data.code === 0) {
                Toast.show({
                    content: '抢单成功！',
                    position: 'center',
                });
                // 抢单成功后刷新订单列表
                fetchOrders();
            } else {
                Toast.show({
                    content: response.data.message || '抢单失败',
                    position: 'center',
                });
            }
        } catch (error) {
            console.error('出现错误，请重试:', error);
            const errorMessage = error.response?.data?.message || '抢单失败，请重试';
            Toast.show({
                content: errorMessage,
                position: 'center',
            });
        }
    };

    const handleRefresh = () => {
        fetchOrders();
    };

    const tabs = [
        { key: 'all', title: '全部' },
        { key: 'nearby', title: '附近' },
        { key: 'highReward', title: '高收益' },
        { key: 'heavy', title: '重物' }
    ];

    // 根据标签筛选订单
    const filteredOrders = orders.filter(order => {
        if (activeTab === 'nearby') {
            // 这里可以根据实际距离计算，暂时用重量模拟
            return order.weight <= 5; // 轻物订单
        }
        if (activeTab === 'highReward') {
            return order.price >= 15; // 高收益订单
        }
        if (activeTab === 'heavy') {
            return order.weight > 5; // 重物订单
        }
        return true; // 全部订单
    });

    // 根据搜索关键词筛选
    const searchFilteredOrders = filteredOrders.filter(order => {
        if (!searchValue) return true;
        const searchLower = searchValue.toLowerCase();
        return (
            order.shopname?.toLowerCase().includes(searchLower) ||
            order.senderAddress?.toLowerCase().includes(searchLower) ||
            order.receiverAddress?.toLowerCase().includes(searchLower) ||
            order.senderName?.toLowerCase().includes(searchLower) ||
            order.receiverName?.toLowerCase().includes(searchLower)
        );
    });

    // 计算配送距离（模拟，实际应该根据GPS坐标计算）
    const calculateDistance = (order) => {
        // 这里可以根据实际位置计算，暂时用重量模拟距离
        const baseDistance = order.weight * 0.5;
        return (baseDistance + Math.random() * 2).toFixed(1);
    };

    // 计算预计配送时间
    const calculateDeliveryTime = (order) => {
        const distance = parseFloat(calculateDistance(order));
        const baseTime = Math.ceil(distance * 3); // 每公里3分钟
        return `${baseTime}分钟`;
    };

    return (
        <div className="fenlei-container">
            {/* 搜索栏 */}
            <div className="search-section">
                <div className="search-input-wrapper">
                    <span className="search-icon">🔍</span>
                    <input
                        type="text"
                        placeholder="搜索物品名称、地址、姓名等"
                        value={searchValue}
                        onChange={(e) => setSearchValue(e.target.value)}
                        className="search-input"
                    />
                </div>
            </div>

            {/* 标签页 */}
            <div className="tabs-section">
                <Tabs activeKey={activeTab} onChange={setActiveTab}>
                    {tabs.map(tab => (
                        <Tabs.Tab title={tab.title} key={tab.key} />
                    ))}
                </Tabs>
            </div>

            {/* 订单列表 */}
            <div className="orders-section">
                <div className="orders-header">
                    <h3>可抢订单 ({searchFilteredOrders.length})</h3>
                    <Button 
                        size="small" 
                        fill="outline" 
                        className="refresh-btn"
                        onClick={handleRefresh}
                        loading={loading}
                    >
                        {loading ? '刷新中' : '刷新'}
                    </Button>
                </div>

                {loading ? (
                    <div className="loading-container">
                        <SpinLoading color="primary" />
                        <p>正在加载订单...</p>
                    </div>
                ) : (
                    <div className="orders-list">
                        {searchFilteredOrders.map(order => (
                            <Card key={order._id} className="order-card">
                                <div className="order-header">
                                    <div className="order-type">
                                        <Tag color="primary">
                                            {order.shopname || '快递配送'}
                                        </Tag>
                                        {order.weight > 8 && (
                                            <span className="heavy-icon">⚡</span>
                                        )}
                                    </div>
                                    <div className="order-reward">
                                        <span className="reward-amount">¥{order.price}</span>
                                        <span className="reward-label">配送费</span>
                                    </div>
                                </div>

                                <div className="order-content">
                                    <h4 className="order-title">
                                        {order.shopname || '快递包裹'}
                                    </h4>
                                    
                                    <div className="order-info">
                                        <div className="info-item">
                                            <span className="info-icon">📦</span>
                                            <span className="info-text">
                                                <strong>取货:</strong> {order.senderAddress}
                                            </span>
                                        </div>
                                        <div className="info-item">
                                            <span className="info-icon">📍</span>
                                            <span className="info-text">
                                                <strong>配送:</strong> {order.receiverAddress}
                                            </span>
                                        </div>
                                    </div>

                                    <div className="order-details">
                                        <div className="detail-row">
                                            <div className="detail-item">
                                                <span className="detail-label">发件人:</span>
                                                <span className="detail-value">{order.senderName}</span>
                                            </div>
                                            <div className="detail-item">
                                                <span className="detail-label">收件人:</span>
                                                <span className="detail-value">{order.receiverName}</span>
                                            </div>
                                        </div>
                                        <div className="detail-row">
                                            <div className="detail-item">
                                                <span className="detail-label">重量:</span>
                                                <span className="detail-value">{order.weight}kg</span>
                                            </div>
                                            <div className="detail-item">
                                                <span className="detail-label">订单号:</span>
                                                <span className="detail-value">{order.orderNo}</span>
                                            </div>
                                        </div>
                                    </div>

                                    <div className="order-meta">
                                        <div className="meta-item">
                                            <span className="meta-icon">⏰</span>
                                            <span>{calculateDeliveryTime(order)}</span>
                                        </div>
                                        <div className="meta-item">
                                            <span className="meta-icon">⭐</span>
                                            <span>{calculateDistance(order)}km</span>
                                        </div>
                                        <div className="meta-item">
                                            <span className="meta-icon">📅</span>
                                            <span>{new Date(order.createTime).toLocaleDateString()}</span>
                                        </div>
                                    </div>

                                    <div className="order-tags">
                                        {order.weight > 8 && (
                                            <Tag fill="outline" size="small" color="warning">
                                                重物
                                            </Tag>
                                        )}
                                        {order.weight <= 3 && (
                                            <Tag fill="outline" size="small" color="success">
                                                轻物
                                            </Tag>
                                        )}
                                        {order.price >= 15 && (
                                            <Tag fill="outline" size="small" color="danger">
                                                高收益
                                            </Tag>
                                        )}
                                    </div>
                                </div>

                                <div className="order-actions">
                                    <Button
                                        className="grab-btn"
                                        color="danger"
                                        fill="solid"
                                        onClick={() => handleGrabOrder(order._id)}
                                    >
                                        立即抢单
                                    </Button>
                                </div>
                            </Card>
                        ))}
                    </div>
                )}

                {!loading && searchFilteredOrders.length === 0 && (
                    <div className="empty-state">
                        <div className="empty-icon">📦</div>
                        <p>暂无可用订单</p>
                        <p className="empty-tip">请稍后再试或切换筛选条件</p>
                    </div>
                )}
            </div>
        </div>
    );
}

export default Fenlei;
